<template>
  <div class="test-container">
    <h2>理财产品测试页面</h2>
    
    <!-- 测试状态 -->
    <el-card class="status-card">
      <h3>测试状态</h3>
      <p>启动时间: {{ startTime }}</p>
      <p>用户信息: {{ userInfo }}</p>
      <p>网络状态: <el-tag :type="networkStatus === 'online' ? 'success' : 'danger'">{{ networkStatus }}</el-tag></p>
    </el-card>
    
    <!-- 测试按钮 -->
    <div class="test-buttons">
      <el-button @click="testGetProducts" :loading="loadingProducts">测试获取产品列表</el-button>
      <el-button @click="testGetBalance" :loading="loadingBalance">测试获取余额</el-button>
      <el-button @click="testPurchase" type="primary" :disabled="!testProduct">测试购买产品</el-button>
      <el-button @click="clearResults" type="info">清空结果</el-button>
    </div>
    
    <!-- 显示结果 -->
    <div class="test-results">
      <h3>测试结果:</h3>
      <el-scrollbar height="400px">
        <pre>{{ testResult }}</pre>
      </el-scrollbar>
    </div>
    
    <!-- 购买测试 -->
    <el-card class="purchase-test" v-if="testProduct">
      <h3>购买测试：</h3>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="产品名称">{{ testProduct.name }}</el-descriptions-item>
        <el-descriptions-item label="最小金额">¥{{ testProduct.minAmount }}</el-descriptions-item>
        <el-descriptions-item label="预期收益率">{{ testProduct.expectedReturn }}%</el-descriptions-item>
        <el-descriptions-item label="投资期限">{{ testProduct.duration }}天</el-descriptions-item>
      </el-descriptions>
      
      <div class="purchase-form">
        <el-form :model="purchaseForm" :rules="purchaseRules" ref="purchaseFormRef" label-width="120px">
          <el-form-item label="投资金额" prop="amount">
            <el-input 
              v-model="purchaseForm.amount" 
              placeholder="输入投资金额"
              style="width: 300px;"
            >
              <template #append>元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="支付密码" prop="paymentPassword">
            <el-input 
              v-model="purchaseForm.paymentPassword" 
              type="password"
              placeholder="请输入支付密码（默认123456）"
              style="width: 300px;"
              show-password
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="executePurchase" :loading="purchaseLoading" type="primary">确认购买</el-button>
            <el-button @click="resetPurchaseForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    
    <!-- 错误日志 -->
    <el-card class="error-log" v-if="errorLog.length > 0">
      <h3>错误日志</h3>
      <el-timeline>
        <el-timeline-item v-for="(error, index) in errorLog" :key="index" :timestamp="error.time" type="error">
          <p><strong>{{ error.message }}</strong></p>
          <pre>{{ error.detail }}</pre>
        </el-timeline-item>
      </el-timeline>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { getProductList, purchaseProduct } from '@/api/finance';
import { getAccountBalance } from '@/api/account';

const testResult = ref('');
const testProduct = ref(null);
const testAmount = ref('');
const testPassword = ref('');
const purchaseLoading = ref(false);

const testGetProducts = async () => {
  try {
    testResult.value = '获取产品列表中...';
    const response = await getProductList({ page: 1, size: 5, status: 1 });
    testResult.value = JSON.stringify(response, null, 2);
    
    if (response.data && response.data.list && response.data.list.length > 0) {
      testProduct.value = response.data.list[0];
      testAmount.value = testProduct.value.minAmount;
    }
  } catch (error) {
    testResult.value = '错误: ' + JSON.stringify(error, null, 2);
  }
};

const testGetBalance = async () => {
  try {
    testResult.value = '获取账户余额中...';
    const response = await getAccountBalance();
    testResult.value = JSON.stringify(response, null, 2);
  } catch (error) {
    testResult.value = '错误: ' + JSON.stringify(error, null, 2);
  }
};

const executePurchase = async () => {
  if (!testProduct.value || !testAmount.value || !testPassword.value) {
    ElMessage.error('请填写完整信息');
    return;
  }
  
  purchaseLoading.value = true;
  try {
    const data = {
      productId: testProduct.value.id,
      amount: parseFloat(testAmount.value),
      paymentPassword: testPassword.value
    };
    
    console.log('发送购买请求:', data);
    const response = await purchaseProduct(data);
    testResult.value = '购买成功: ' + JSON.stringify(response, null, 2);
    ElMessage.success('购买成功');
  } catch (error) {
    console.error('购买失败:', error);
    testResult.value = '购买失败: ' + JSON.stringify(error, null, 2);
    ElMessage.error(`购买失败: ${error.message || error}`);
  } finally {
    purchaseLoading.value = false;
  }
};

const testPurchase = () => {
  if (!testProduct.value) {
    ElMessage.warning('请先获取产品列表');
    return;
  }
  // 只是滚动到购买测试区域
  const purchaseTest = document.querySelector('.purchase-test');
  if (purchaseTest) {
    purchaseTest.scrollIntoView({ behavior: 'smooth' });
  }
};
</script>

<style scoped>
.test-container {
  padding: 20px;
}

.test-buttons {
  margin-bottom: 20px;
}

.test-buttons .el-button {
  margin-right: 10px;
}

.test-results {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
  margin: 20px 0;
}

.test-results pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  max-height: 400px;
  overflow-y: auto;
}

.purchase-test {
  background-color: #fafafa;
  padding: 15px;
  border-radius: 4px;
  border: 1px solid #ddd;
}
</style>
